package com.example.browser;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by dhs on 2018/7/27.
 */

public class bookmark extends Activity {
    private ListView lv,folder_list;
    private MyDatabaseHelper dbHelper;



    private static final String FILENAME="YX";
    private static final String TABLENAME = "bookmarkDB";
    private String get_title,get_url;
    private int get_id;
    private String titler, url;
    int id;
    private TextView text_title, text_url;
    private ArrayList arrayList=new ArrayList();
    private ArrayList arrayList2=new ArrayList();
    private boolean if_exist;
    private boolean if_folderexist;

    public static bookmark instance = null;



    private EditText search_bookmark;
    private LinearLayout addfolder,addweb,history,hb;
    private int counthb=0;
    private int counthbfolder=0;
    SharedPreferences share;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bookmarklist);
        instance = this;


        lv=(ListView)findViewById(R.id.bookmark_list);
        folder_list=(ListView)findViewById(R.id.folder_list);
        addfolder=(LinearLayout)findViewById(R.id.addfolder) ;
        addweb=(LinearLayout)findViewById(R.id.addweb) ;
        history=(LinearLayout)findViewById(R.id.history) ;
        hb=(LinearLayout)findViewById(R.id.hb) ;
        share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        search_bookmark=(EditText)findViewById(R.id.search_bookmark) ;
        //监听编辑框
        search_bookmark.addTextChangedListener(new EditChangedListener());
        queryinfo();
        queryfolder();
        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
        onclick();
        history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent();
                intent.setClass(bookmark.this,history.class);
                startActivityForResult(intent,1);
            }
        });



    }

    private void onclick() {
        hb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                counthb=0;
                new AlertDialog.Builder(bookmark.this)
                        .setItems(new String[]{"合并页面书签", "合并书签文件夹"}, (dialog, which) -> {

                            switch (which) {
                                case 0:
                                    AlertDialog hb;
                                    hb= new AlertDialog.Builder(bookmark.this).setTitle("要保证在yunxi文件夹下有dmbrowser.db")
                                            .setMessage("这个会把别人这个页面书签添加进去且不会重复")
                                            .setPositiveButton("确定合并", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    CustomSQLTools s = new CustomSQLTools();
                                                    SQLiteDatabase database = s.openDatabase(getApplicationContext());
                                                    Cursor cursor = database.query("bookmarkDB", null, null, null, null, null, "id desc");
                                                    if (cursor != null && cursor.getCount() > 0) {

                                                        while(cursor.moveToNext()) {
                                                            get_id=cursor.getInt(0);//得到int型的自增变量
                                                            get_title = cursor.getString(1);
                                                            get_url = cursor.getString(2);
                                                            selecthb(get_title,get_url);
                                                        }
                                                    }
                                                    Toast.makeText(bookmark.this, "一共添加了"+counthb+"条数据", Toast.LENGTH_SHORT).show();
                                                    cursor.close();
                                                    database.close();
                                                    arrayList.clear();
                                                    queryinfo();
                                                    queryfolder();
                                                    setListViewHeightBasedOnChildren(lv);
                                                    setListViewHeightBasedOnChildren(folder_list);
                                                }
                                            })
                                            .setNeutralButton("确定合并并修改链接标题", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    CustomSQLTools s = new CustomSQLTools();
                                                    SQLiteDatabase database = s.openDatabase(getApplicationContext());
                                                    Cursor cursor = database.query(TABLENAME, null, null, null, null, null, "id desc");
                                                    if (cursor != null && cursor.getCount() > 0) {

                                                        while(cursor.moveToNext()) {
                                                            get_id=cursor.getInt(0);//得到int型的自增变量
                                                            get_title = cursor.getString(1);
                                                            get_url = cursor.getString(2);
                                                            selecthbtitle(get_title,get_url);
                                                        }
                                                    }
                                                    cursor.close();
                                                    database.close();
                                                    SharedPreferences.Editor edit=share.edit();
                                                    edit.putString(TABLENAME+"re", "还原");//存
                                                    edit.commit();
                                                    queryinfo();
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                }
                                            })
                                            .create();
                                    hb.show();
                                    break;
                                case 1:
                                    AlertDialog hbfolder;
                                    counthbfolder=0;
                                    hbfolder= new AlertDialog.Builder(bookmark.this).setTitle("要保证在yunxi文件夹下有dmbrowser.db")
                                            .setMessage("这个会把别人分享的书签文件夹与自己的合并起来")
                                            .setPositiveButton("确定合并", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {
                                                    CustomSQLTools s = new CustomSQLTools();
                                                    SQLiteDatabase database = s.openDatabase(getApplicationContext());
                                                    Cursor cursor = database.query("addfolderDB", null, null, null, null, null, "id desc");
                                                    if (cursor != null && cursor.getCount() > 0) {

                                                        while(cursor.moveToNext()) {
                                                            get_id=cursor.getInt(0);//得到int型的自增变量
                                                            get_title = cursor.getString(1);
                                                            get_url = cursor.getString(2);
                                                            selecthbfolder(get_url,get_title);

                                                        }
                                                    }
                                                    Toast.makeText(bookmark.this, "一共添加了"+counthbfolder+"个文件夹", Toast.LENGTH_SHORT).show();
                                                    cursor.close();
                                                    database.close();
                                                    arrayList2.clear();
                                                    queryinfo();
                                                    queryfolder();
                                                    setListViewHeightBasedOnChildren(lv);
                                                    setListViewHeightBasedOnChildren(folder_list);
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialogInterface, int i) {

                                                }
                                            })
                                            .create();
                                    hbfolder.show();
                                    break;
                            }
                        })
                        .show();



            }
        });
        addweb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog addwebdialog = new Dialog(bookmark.this, R.style.MyDialogActivityStyle);
                View addwebview = View.inflate(bookmark.this, R.layout.dialogaddweb, null);
                addwebdialog.setContentView(addwebview);
                addwebdialog.setCanceledOnTouchOutside(true);
                Window window = addwebdialog.getWindow();//得到对话框的窗口．
                WindowManager.LayoutParams wl = window.getAttributes();
                WindowManager windowManager = getWindowManager();
                Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
                wl.width = (int)(display.getWidth() * 1); //设置宽度
                wl.height = (int)(display.getHeight() * 0.35);
                wl.alpha = 1f;// 设置对话框的透明度,1f不透明
                window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
                window.setAttributes(wl);
                text_title = (EditText) addwebview.findViewById(R.id.title);
                text_url = (EditText) addwebview.findViewById(R.id.url);
                text_title.setFocusable(true);
                text_title.setFocusableInTouchMode(true);
                text_title.requestFocus();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                                   public void run() {
                                       InputMethodManager inputManager =
                                               (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                       inputManager.showSoftInput(text_title, 0);
                                   }
                               },
                        200);

                //显示详细信息

                addwebview.findViewById(R.id.addweb).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(TextUtils.isEmpty(text_title.getText().toString())||TextUtils.isEmpty(text_url.getText().toString())){
                            Toast.makeText(bookmark.this, "网址名称和网址地址不能为空", Toast.LENGTH_SHORT).show();
                        }else {
                            select(text_title.getText().toString(),text_url.getText().toString());
                            addwebdialog.dismiss();
                        }
                        queryinfo();
                        setListViewHeightBasedOnChildren(lv);
                        setListViewHeightBasedOnChildren(folder_list);
                    }
                });

                addwebview.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        addwebdialog.dismiss();
                    }
                });

                addwebdialog.show();

            }
        });

        addfolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog addfolderdialog = new Dialog(bookmark.this, R.style.MyDialogActivityStyle);
                View addfolderview = View.inflate(bookmark.this, R.layout.dialogupfolder, null);
                addfolderdialog.setContentView(addfolderview);
                addfolderdialog.setCanceledOnTouchOutside(true);
                Window window = addfolderdialog.getWindow();//得到对话框的窗口．
                WindowManager.LayoutParams wl = window.getAttributes();
                WindowManager windowManager = getWindowManager();
                Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
                wl.width = (int)(display.getWidth() * 1); //设置宽度
                wl.height = (int)(display.getHeight() * 0.3);
                wl.alpha = 1f;// 设置对话框的透明度,1f不透明
                window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
                window.setAttributes(wl);
                text_title = (EditText) addfolderview.findViewById(R.id.foldername);

                text_title.setFocusable(true);
                text_title.setFocusableInTouchMode(true);
                text_title.requestFocus();
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                                   public void run() {
                                       InputMethodManager inputManager =
                                               (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                       inputManager.showSoftInput(text_title, 0);
                                   }
                               },
                        200);

                //显示详细信息

                addfolderview.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(TextUtils.isEmpty(text_title.getText().toString())){
                            Toast.makeText(bookmark.this, "分组名称还没写哦", Toast.LENGTH_SHORT).show();
                        }else {

                            addfolder_table(text_title.getText().toString());
                            addfolderdialog.dismiss();
                        }
                        queryinfo();
                        setListViewHeightBasedOnChildren(lv);
                        setListViewHeightBasedOnChildren(folder_list);
                    }
                });

                addfolderview.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        addfolderdialog.dismiss();
                    }
                });

                addfolderdialog.show();

                //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";
                //String sql = "select * from " + TABLENAME + " where name like '%"+ username + "%'";
                //String sql = "select * from bookmarkDB where url like '%"+ url + "%'OR title like '%"+ url + "%'";



            }
        });

        //点击函数：
        folder_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_folderexist) {

                    Intent intent = new Intent(bookmark.this,folder.class);//没有任何参数（意图），只是用来传递数据
                    intent.putExtra("foldername", folderquery_by_id2(position));
                    startActivity(intent);

                }


            }
        });

        //长按选择删除
        folder_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (if_folderexist)
                    new AlertDialog.Builder(bookmark.this)
                            .setItems(new String[]{"查看/修改/权限", "删除该分组"}, (dialog, which) -> {

                                switch (which) {
                                    case 0:
                                        folder_infomation(position);
                                        break;
                                    case 1:
                                        AlertDialog dialogfolder = new AlertDialog.Builder(bookmark.this)
                                                .setTitle("确定删除吗？")//设置对话框的标题
                                                //设置对话框的按钮
                                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.dismiss();
                                                    }
                                                })
                                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        deletefolder(position);
                                                        dialog.dismiss();
                                                    }
                                                }).create();
                                        dialogfolder.show();
                                        break;
                                }
                            })
                            .show();

                return true;
            }
        });

        //点击函数：
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exist) {
                    Intent intent = new Intent(bookmark.this,webview.class);//没有任何参数（意图），只是用来传递数据
                    intent.putExtra("searchText", query_by_id(position));
                    startActivity(intent);
                    finish();
                }


            }
        });
        //长按选择删除
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (if_exist)
                    dialog_bottom(position);
                return true;
            }
        });
    }
    private void hbfolder(String foldertable){
        dbHelper = new MyDatabaseHelper(bookmark.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="create table if not exists'"+foldertable+"'(id integer primary key autoincrement," +
                "title text," +
                "url text)";

        db.execSQL(sql);
        //为文件夹输入数据
        CustomSQLTools s = new CustomSQLTools();
        SQLiteDatabase database = s.openDatabase(getApplicationContext());
        Cursor cursor = database.query(foldertable, null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                get_id = cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                ContentValues values = new ContentValues();
                values.put("title", get_title);
                values.put("url", get_url);
                //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
                db.insert(foldertable,null,values);
                cursor.close();
                database.close();
                db.close();
            }
        }
    }
    //查询数据库里的字段
    public void selecthbfolder(String foldertable,String foldername) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";
        //String sql = "select * from " + TABLENAME + " where name like '%"+ username + "%'";
        String sql ="SELECT * FROM addfolderDB WHERE foldername='"+foldername+"'";

        Cursor result=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if(result.moveToFirst())//如果结果集的第一行有数据
        {
            //https://codingdict.com/questions/117721
            ContentValues values = new ContentValues();
            values.put("foldername",result.getString(1)+"新增");
            values.put("foldertable",result.getString(2));
            //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
            db.insert("addfolderDB",null,values);
            hbfolder(result.getString(2));
            counthbfolder++;
            result.close();
            db.close();
        }
        else {
            addfolder(foldername,foldertable);
            hbfolder(foldertable);
            counthbfolder++;
            result.close();
            db.close();

        }
    }
    //查询数据库里的字段
    public void selecthbtitle(String title,String url) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";
        //String sql = "select * from " + TABLENAME + " where name like '%"+ username + "%'";
        String sql ="SELECT * FROM "+TABLENAME+" WHERE url='"+url+"'";

        Cursor result=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if(result.moveToFirst())//如果结果集的第一行有数据
        {
            get_id=result.getInt(0);//得到int型的自增变量
            get_title = result.getString(1);
            get_url = result.getString(2);
            update(get_id, title, get_url);
            result.close();
            db.close();


        }
        else {
            ContentValues values = new ContentValues();
            values.put("title", title);
            values.put("url", url);
            //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
            db.insert(TABLENAME,null,values);
            counthb++;
            result.close();
            db.close();

        }
    }
    //查询数据库里的字段
    public void selecthb(String title,String url) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";
        //String sql = "select * from " + TABLENAME + " where name like '%"+ username + "%'";
        String sql ="SELECT * FROM "+TABLENAME+" WHERE url='"+url+"'";

        Cursor result=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if(result.moveToFirst())//如果结果集的第一行有数据
        {
            //https://codingdict.com/questions/117721
            //Toast.makeText(WebView.this,result.getString(1), Toast.LENGTH_SHORT).show();
            result.close();
            db.close();
        }
        else {
            ContentValues values = new ContentValues();
            values.put("title", title);
            values.put("url", url);
            //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
            db.insert(TABLENAME,null,values);
            counthb++;
            result.close();
            db.close();

        }
    }
    private void addfolder_table(String foldername){
        dbHelper = new MyDatabaseHelper(bookmark.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        SharedPreferences share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor edit=share.edit();
        String foldertable ="table";
        int count = share.getInt("TABLENAME",0)+1;
        String androidId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        String sql="create table if not exists'"+foldertable+androidId+count+"'(id integer primary key autoincrement," +
                "title text," +
                "url text)";
        edit.putInt("TABLENAME",count);
        edit.commit();
        db.execSQL(sql);
        db.close();
        selectfoldder(foldername,foldertable+androidId+Integer.toString(share.getInt("TABLENAME",0)));
    }

    //查询数据库里的字段
    public void select(String title,String url) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String sql ="SELECT * FROM bookmarkDB WHERE url='"+url+"'";
        Cursor result=db.rawQuery(sql, null);
        if(result.moveToFirst())
        {

            Toast.makeText(bookmark.this, "已存在书签中,名称为———"+result.getString(1), Toast.LENGTH_LONG)
                    .show();
            result.close();
            db.close();
        }
        else {
            addweb(title,url);
            result.close();
            db.close();

        }
    }

    public void addweb(String title,String url){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(bookmark.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title", title);
        values.put("url", url);

        db.insert("bookmarkDB",null,values);
        Toast.makeText(bookmark.this,"添加成功",Toast.LENGTH_SHORT).show();
        queryinfo();
        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }


    //url详细信息对话框
    public void folder_infomation(final int position){
        final Dialog dialog = new Dialog(bookmark.this, R.style.MyDialogActivityStyle);
        View view = View.inflate(bookmark.this, R.layout.dialogupfolder, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();//得到对话框的窗口．
        WindowManager.LayoutParams wl = window.getAttributes();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
        wl.width = (int)(display.getWidth() * 1); //设置宽度
        wl.height = (int)(display.getHeight() * 0.3);
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
        window.setAttributes(wl);
        text_title = (EditText) view.findViewById(R.id.foldername);


        text_title.setFocusable(true);
        text_title.setFocusableInTouchMode(true);
        text_title.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(text_title, 0);
                           }
                       },
                200);

        //显示详细信息

        text_title.setText(folderquery_name(position));
        view.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                update_foldername(folderquery_by_id(position),text_title.getText().toString(),folderquery_by_id2(position));
                //刷新UI
                queryfolder();
                dialog.dismiss();

            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();


    }

    //修改数据
    public void update_foldername(int id,String title,String url) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="update addfolderDB set foldertable='" + url + "',foldername='" + title + "' where id="+ id;
        db.execSQL(sql);
        db.close();
    }
    //删除函数：
    public void deletefolder(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //删除文件夹对应的表
        String sql="drop table if exists "+folderquery_by_id2(position);
        db.delete("addfolderDB","id=?",new String[] {String.valueOf(arrayList2.get(position))});
        db.execSQL(sql);
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList2.clear();
        queryinfo();
        queryfolder();
        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }

    //全部删除
    public void delete_allfolder(){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from addfolderDB", null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete("addfolderDB","id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        queryfolder();
        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }

    public int folderquery_by_id(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from addfolderDB", null);
        while (cursor.moveToNext()) {
            url=cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList2.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return id;
    }

    public String folderquery_by_id2(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from addfolderDB", null);
        while (cursor.moveToNext()) {
            url=cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList2.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return url;
    }
    public String folderquery_name(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from addfolderDB", null);
        while (cursor.moveToNext()) {
            url=cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList2.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return titler;
    }

    //数据库添加数据(书签表)
    public void move(String title,String url,String foldername){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(bookmark.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title",title);
        values.put("url", url);

        db.insert(foldername,null,values);

        Toast.makeText(bookmark.this,"添加成功",Toast.LENGTH_SHORT).show();
    }
    //查询数据库里的字段
    public void selectfoldder(String foldername,String foldertable) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        String sql ="SELECT * FROM addfolderDB WHERE foldername='"+foldername+"'";

        Cursor result=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if(result.moveToFirst())//如果结果集的第一行有数据
        {

            Toast.makeText(bookmark.this, result.getString(1)+"已存在", Toast.LENGTH_LONG)
                    .show();
            result.close();
            db.close();

        }
        else {
            addfolder(foldername,foldertable);
            result.close();
            db.close();

        }


    }
    //文件夹表添加数据
    public void addfolder(String foldername,String foldertable){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(bookmark.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("foldername", foldername);
        values.put("foldertable", foldertable);

        db.insert("addfolderDB",null,values);
        Toast.makeText(bookmark.this,"添加成功",Toast.LENGTH_SHORT).show();
        arrayList2.clear();
        //刷新UI
        queryfolder();
        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }

    //数据库逆序查询函数：
    public void queryfolder(){
        final ArrayList<HashMap<String, Object>> listItem2 = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        Cursor cursor = db.query("addfolderDB", null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_folderexist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);

                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("foldername", get_title);
                map.put("folderpic", String.valueOf(R.drawable.folder));
                arrayList2.add(get_id);
                listItem2.add(map);

                SimpleAdapter mSimpleAdapter2 = new SimpleAdapter(this,listItem2,R.layout.folderzujian,
                        new String[] {"foldername","folderpic"},
                        new int[] {R.id.foldername,R.id.folderpic});
                folder_list.setAdapter(mSimpleAdapter2);
                folder_list.setVisibility(View.VISIBLE);
            }
        }else {
            if_folderexist=false;

            folder_list.setVisibility(View.GONE);
        }
        cursor.close();
        db.close();
    }


    //bookmarkDB删除函数：
    public void delete(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("bookmarkDB","id=?",new String[] {String.valueOf(arrayList.get(position))});
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();

        arrayList.clear();
        queryinfo();

        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }

    //全部删除
    public void delete_all(){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete("bookmarkDB","id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
        //删除后清空数组，重新放入数据，刷新UI
        arrayList.clear();
        //刷新UI
        queryinfo();

        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }

    //bookmarkDB全部删除对话框
    public void delete_all_dialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete_all();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    //数据库逆序查询函数：
    public void queryinfo(){
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写

        Cursor cursor = db.query("bookmarkDB", null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"title","url"},
                        new int[] {R.id.title,R.id.url});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "暂时没有");
            map.put("url", "");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"title","url"},
                    new int[] {R.id.title,R.id.url});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }
    //按值查找：
    public String query_by_id(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        while (cursor.moveToNext()) {
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return url;
    }
    public int query_by_id2(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        while (cursor.moveToNext()) {
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return id;
    }
    public String query_by_id3(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        while (cursor.moveToNext()) {
            url = cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return titler;
    }
    //修改数据
    public void update(int id, String title, String url) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql="update bookmarkDB set url='" + url + "',title='" + title + "' where id="+ id;
        db.execSQL(sql);
        db.close();
        queryinfo();
    }

    //url详细信息对话框
    public void url_infomation(final int position){
        final Dialog dialog = new Dialog(bookmark.this, R.style.MyDialogActivityStyle);
        View view = View.inflate(bookmark.this, R.layout.modification, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();//得到对话框的窗口．
        WindowManager.LayoutParams wl = window.getAttributes();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
        wl.width = (int)(display.getWidth() * 1); //设置宽度
        wl.height = (int)(display.getHeight() * 0.35);
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
        window.setAttributes(wl);
        text_title = (EditText) view.findViewById(R.id.textView2);
        text_url = (EditText) view.findViewById(R.id.textView3);

        text_title.setFocusable(true);
        text_title.setFocusableInTouchMode(true);
        text_title.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(text_title, 0);
                           }
                       },
                200);

        //显示详细信息
        text_url.setText(query_by_id(position));
        text_title.setText(titler);
        view.findViewById(R.id.upDate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                update(query_by_id2(position),text_title.getText().toString(),text_url.getText().toString());
                //刷新UI
                queryinfo();
                queryfolder();
                setListViewHeightBasedOnChildren(lv);
                setListViewHeightBasedOnChildren(folder_list);
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();


    }

    //底部对话框
    public void dialog_bottom(final int position){
        //弹出对话框

        final Dialog dialog = new Dialog(bookmark.this, R.style.MyDialogActivityStyle);
        View view = View.inflate(bookmark.this, R.layout.bookmarkoption, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window window = dialog.getWindow();//得到对话框的窗口．
        WindowManager.LayoutParams wl = window.getAttributes();

        dialog.show();
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
//                wl.x = x;//设置对话框的位置．0为中间
//                wl.y = y;
        wl.width = (int)(display.getWidth() * 1); //设置宽度
        wl.height = (int)(display.getHeight() * 0.4);
        wl.alpha = 1f;// 设置对话框的透明度,1f不透明
        window.setGravity(Gravity.BOTTOM);//底部出现//设置显示在中间
        window.setAttributes(wl);
        //点击事件
        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消对话框
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.copy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label",query_by_id(position));
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                Toast.makeText(bookmark.this, "已复制", Toast.LENGTH_SHORT).show();
                dialog.dismiss();


            }
        });
        view.findViewById(R.id.move).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(bookmark.this,moveselect.class);
                intent.putExtra("id",Integer.toString(query_by_id2(position)));
                intent.putExtra("title",query_by_id3(position));
                intent.putExtra("url",query_by_id(position));
                startActivityForResult(intent,1);

                dialog.dismiss();
            }
        });
        view.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除制定position，并取消对话框
                delete(position);
                dialog.dismiss();

            }
        });
        view.findViewById(R.id.lookup).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //查看、修改
                url_infomation(position);
                dialog.dismiss();

            }
        });
        view.findViewById(R.id.clear_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //全部删除
                dialog.dismiss();
                delete_all_dialog();

            }
        });
    }

    //数据库逆序查询函数：
    public void queryinfo2( String url ){
        final ArrayList<HashMap<String, Object>> listItem = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        arrayList.clear();
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";

        String sql = "select * from bookmarkDB where url like '%"+ url + "%'OR title like '%"+ url + "%'";
        Cursor cursor=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);
                get_url = cursor.getString(2);
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("title", get_title);
                map.put("url", get_url);
                arrayList.add(get_id);
                listItem.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                        new String[] {"title","url"},
                        new int[] {R.id.title,R.id.url});
                lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }
        else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("title", "没有找到");
            map.put("url", "");
            listItem.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem,R.layout.bookmarkzujian,
                    new String[] {"title","url"},
                    new int[] {R.id.title,R.id.url});
            lv.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }

        cursor.close();
        db.close();
    }
    //计算listview高度
    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {

            View listItem = listAdapter.getView(i, null, listView);

            listItem.measure(0, 0);

            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        params.height += 5;//if without this statement,the listview will be a little short

        listView.setLayoutParams(params);

    }

    //监听编辑框--https://www.jb51.net/article/135392.htm
    //https://blog.csdn.net/ycwol/article/details/46594275
    class EditChangedListener implements TextWatcher {
        public void afterTextChanged(Editable arg0) {
// 文字改变后出发事件
            String content = search_bookmark.getText().toString();
            //若输入框内容为空按钮可点击，字体为蓝色
            if (!content.isEmpty()) {
                queryinfo2(search_bookmark.getText().toString());
                setListViewHeightBasedOnChildren(lv);
                setListViewHeightBasedOnChildren(folder_list);
            } else {
                queryinfo();
                setListViewHeightBasedOnChildren(lv);
                setListViewHeightBasedOnChildren(folder_list);
            }

        }
        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
// TODO Auto-generated method stub

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub

        }
    };

    //获取返回搜索url
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if(resultCode==1){

                // int resultid=Integer.parseInt(data.getStringExtra("move"));
                // deleteid(resultid);


            }
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //finish();点击窗口外部区域 弹窗消失
        //点击空白处关闭键盘
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if(imm.isActive()&&getCurrentFocus()!=null){
            if (getCurrentFocus().getWindowToken()!=null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
            //刷新UI
            queryinfo();
            queryfolder();
            setListViewHeightBasedOnChildren(lv);
            setListViewHeightBasedOnChildren(folder_list);
            search_bookmark.setText("");
        }
        return true;
    }



    @Override
    protected void onRestart() {
        super.onRestart();
        //刷新UI
        queryinfo();
        queryfolder();
        setListViewHeightBasedOnChildren(lv);
        setListViewHeightBasedOnChildren(folder_list);
    }


}